import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { message } from "antd";
import axios from 'axios';

// 定义组件属性类型，此处登录页暂时无外部传入属性，可根据需求扩展
interface LoginProps {}

const Login: React.FC<LoginProps> = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [rememberMe, setRememberMe] = useState(false);
  const [error, setError] = useState("");
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  // 添加显示密码状态
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const savedLoginData = localStorage.getItem('loginData');
    if (savedLoginData) {
      const { username: savedUsername, password: savedPassword, rememberMe: savedRememberMe } = JSON.parse(savedLoginData);
      if (savedRememberMe) {
        setUsername(savedUsername || '');
        setPassword(savedPassword || '');
        setRememberMe(savedRememberMe);
      }
    }
  }, []);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError('');
    setIsLoggingIn(true);
    
    // 增强表单验证
    if (!username.trim()) {
      setError('请输入用户名');
      setIsLoggingIn(false);
      return;
    }
    if (!password.trim()) {
      setError('请输入密码');
      setIsLoggingIn(false);
      return;
    }
    if (username.length < 3) {
      setError('用户名至少3个字符');
      setIsLoggingIn(false);
      return;
    }
    if (password.length < 6) {
      setError('密码至少6个字符');
      setIsLoggingIn(false);
      return;
    }

    
    try {
      // 模拟API调用 - 实际项目中替换为真实登录接口
      const response = await axios.post('http://localhost:3000/login', {
        username,
        password
      });
      
      // 假设后端返回{ success: true, token, userInfo }
      if (response.data.success) {
        if (rememberMe) {
          // 安全存储：仅存储用户名，不存储密码
          localStorage.setItem('rememberedUsername', username);
          // 实际项目中应使用HttpOnly Cookie存储token
        }
        localStorage.setItem('username', username);
        message.success('登录成功', 1, () => {
          navigate('/sales');
        });
      } else {
        setError(response.data.message || '登录失败，请检查用户名和密码');
      }
    } catch (err) {
      console.error('登录错误:', err);
      if (axios.isAxiosError(err)) {
        setError(err.response?.data?.message || '网络错误，请稍后重试');
      } else {
        setError('登录过程中发生错误');
      }
    }
    setIsLoggingIn(false);
  };

  return (
    <div
      style={{
        background: "/supermarket.png", // 使用渐变背景
        height: "100vh",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        color: "#fff",
        fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif", // 使用更现代的字体
      }}
    >
      <form
        onSubmit={handleSubmit}
        style={{
          backgroundColor: "rgba(255, 255, 255, 0.1)", // 调整表单背景透明度
          padding: "30px 50px", // 增加内边距
          borderRadius: "12px", // 增大圆角
          boxShadow: "0 10px 25px rgba(0, 0, 0, 0.3)", // 增强阴影效果
          width: "30vw",
          minWidth: "300px", // 设置最小宽度
          backdropFilter: "blur(10px)", // 添加毛玻璃效果
          border: "1px solid rgba(255, 255, 255, 0.1)", // 添加边框
        }}
      >
        <h2
          style={{
            textAlign: "center",
            marginBottom: "30px",
            color: "#fff",
            textShadow: "0 2px 4px rgba(0, 0, 0, 0.2)",
          }}
        >
          登录
        </h2>
        {error && (
          <div
            style={{
              color: "#ff6b6b", // 使用更鲜明的红色
              marginBottom: "20px",
              textAlign: "center",
              textShadow: "0 1px 2px rgba(0, 0, 0, 0.2)",
            }}
          >
            {error}
          </div>
        )}
        <div
          style={{
            marginBottom: "20px",
            position: "relative",
          }}
        >
          <label
            htmlFor="username"
            style={{
              display: "block",
              marginBottom: "8px",
              color: "#f0f0f0",
              fontSize: "14px",
            }}
          >
            用户名
          </label>
          <input
            type="text"
            id="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            style={{
              width: "100%",
              padding: "12px 0px",
              borderRadius: "8px",
              border: "1px solid rgba(255, 255, 255, 0.2)",
              backgroundColor: "rgba(255, 255, 255, 0.1)",
              color: "#fff",
              outline: "none",
              transition: "border-color 0.3s ease",
              // ':focus': { borderColor: "#4a90e2" }
            }}
          />
        </div>
        <div
          style={{
            marginBottom: "20px",
            position: "relative",
          }}
        >
          <label
            htmlFor="password"
            style={{
              display: "block",
              marginBottom: "8px",
              color: "#f0f0f0",
              fontSize: "14px",
            }}
          >
            密码
          </label>
          <div style={{ position: "relative" }}>
            <input
              type={showPassword ? "text" : "password"}
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              style={{
                width: "100%",
                padding: "12px 0px",
                borderRadius: "8px",
                border: "1px solid rgba(255, 255, 255, 0.2)",
                backgroundColor: "rgba(255, 255, 255, 0.1)",
                color: "#fff",
                outline: "none",
                transition: "border-color 0.3s ease",
                // ':focus': { borderColor: "#4a90e2" }
              }}
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              style={{
                width: "40px",
                height: "30px",
                position: "absolute",
                right: "10px",
                top: "50%",
                transform: "translateY(-50%)",
                background: "none",
                backgroundColor: "rgba(255, 255, 255, 0.1)",
                border: "1px solid rgba(255, 255, 255, 0.2)",
                color: "#f0f0f0",
                cursor: "pointer",
                padding: "0",
                fontSize: "14px",
                // transition: "border-color 0.3s ease",
              }}
            >
              {showPassword ? "隐藏" : "显示"}
            </button>
          </div>
        </div>
        <div
          style={{
            marginBottom: "25px",
            display: "flex",
            alignItems: "center",
          }}
        >
          <input
            type="checkbox"
            checked={rememberMe}
            onChange={(e) => setRememberMe(e.target.checked)}
            style={{
              marginRight: "8px",
              width: "18px",
              height: "18px",
            }}
          />
          <label
            style={{
              color: "#f0f0f0",
              fontSize: "14px",
              cursor: "pointer",
            }}
          >
            记住我
          </label>
        </div>
        <button
          type="submit"
          disabled={isLoggingIn}
          style={{
            width: "100%",
            padding: "14px",
            borderRadius: "8px",
            border: "none",
            backgroundColor: "#4a90e2",
            color: "#fff",
            cursor: isLoggingIn ? "not-allowed" : "pointer",
            fontSize: "16px",
            fontWeight: "500",
            transition: "background-color 0.3s ease",
            // ':hover': { backgroundColor: "#357abd" },
            // ':disabled': { backgroundColor: "#7f8c8d" }
          }}
        >
          {isLoggingIn ? "登录中..." : "登录"}
        </button>
      </form>
    </div>
  );
};

export default Login;
